package controller

import (
	"gin-demo/dao"
	"gin-demo/model"
	"gin-demo/req"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

func init() {
	log.Println(">>>> get database connection start <<<<")
}

// localhost:9090/user/query?id=2&name=hello
func QueryParam(context *gin.Context) {
	println(">>>> query user by url params action start <<<<")
	id := context.Query("id")
	//name := context.Request.URL.Query().Get("name")

	var user model.User

	dao.DB.Where(&user, " id = ?", id)

	context.JSON(200, gin.H{
		"result": user,
	})
}

// localhost:9090/user/get/2/hello
func QueryById(c *gin.Context) {
	println(">>>> get user by id and name action start <<<<")

	//resultMap := make(map[string]string)
	reqData := map[string]string{
		"username": c.Param("username"),
		"id":       c.Param("id"),
	}
	c.JSON(200, gin.H{
		"result": 1,
		"data":   reqData,
	})
}

// localhost:9090/user/login
func Login(c *gin.Context) {
	println(">>>> login action start <<<<")
	var form req.LoginReq
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	if form.Username != "admin" || form.Password != "123456" {
		c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
}

// json格式数据
func InsertNewUser(context *gin.Context) {
	println(">>>> insert controller action start <<<<")
	var user model.User

	// 使用ioutile读取二进制数据
	//bytes,err := ioutil.ReadAll(context.Request.Body)
	//if err != nil {
	//  log.Fatal(err)
	//}
	//err = json.Unmarshal(bytes,&user)

	// 直接将结构体和提交的json参数作绑定
	err := context.ShouldBindJSON(&user)

	if err != nil {
		checkError(err)
		return
	}
	// 写入数据库
	if err1 := dao.DB.Create(&user).Error; err1 != nil {
		checkError(err1)
		return
	}
	context.JSON(200, gin.H{
		"success": true,
	})
}

// JSON输出
func JSON(c *gin.Context) {
	c.JSON(200, gin.H{
		"html": "<b>Hello, world!</b>",
	})
}

// JSON输出
func PureJSON(c *gin.Context) {
	c.PureJSON(200, gin.H{
		"html": "<b>Hello, world!</b>",
	})
}

// form表单提交
func PostForm(context *gin.Context) {
	println(">>>> bind form post params action start <<<<")

}

//index 页面（渲染）
func Index(c *gin.Context) {
	c.HTML(http.StatusOK, "index.html", gin.H{
		"title": "Main website",
	})
}

// 跳转html
func RenderForm(context *gin.Context) {
	println(">>>> render to html action start <<<<")

	context.Header("Content-Type", "text/html; charset=utf-8")
	context.HTML(200, "hello.html", gin.H{})
}

func checkError(e error) {
	if e != nil {
		log.Fatal(e)
	}
}
